package org.example.secondkill.exception;

import org.example.secondkill.response.BaseResponse;
import org.example.secondkill.response.ResultCode;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@ControllerAdvice
@ResponseBody
public class BaseExceptionHandle {
    @ExceptionHandler(value = Exception.class)
    public BaseResponse<String> exceptionHandle(HttpServletRequest request, Exception e) {
        if (e instanceof BaseException) {
            return BaseResponse.error(((BaseException) e).getResultCode());
        } else if (e instanceof BindException) {
            BindException exception = (BindException) e;
            List<ObjectError> errors = exception.getAllErrors();
            ObjectError objectError = errors.get(0);
            String msg = objectError.getDefaultMessage();
            return BaseResponse.error(ResultCode.BIND_ERROR);
        } else {
            return BaseResponse.error(ResultCode.SERVER_ERROR);
        }
    }
}
